package com.nf.health.app.inquiry.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.CustomChatPrimaryMenu;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.util.PathUtil;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.PictureActivity;
import com.nf.health.app.http.ImageUpLoader;
import com.nf.health.app.inquiry.adapter.DetailGridViewAdapter;
import com.nf.health.app.inquiry.adapter.InquiryChatListAdapter;
import com.nf.health.app.inquiry.bean.InquiryDetailBean;
import com.nf.health.app.models.ChatMessageVo;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.DialogHelp;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 问诊-聊天
 *
 * @author changpeng
 */
public class InquiryChatActivity extends BaseActivity implements View.OnClickListener {

    private static final int ITEM_PICTURE = 1;
    private static final int ITEM_TAKE_PICTURE = 2;
    private static final String USER_TEXT_TYPE = "1";
    private static final String DOCTOR_TEXT_TYPE = "2";
    private static final String USER_IMG_TYPE = "3";
    private static final String DOCTOR_IMG_TYPE = "4";
    private static final String USER_REPLY_INQUIRY = "userReplyInquiry";
    private static final String USER_REPLY_INQUIRY_IMG = "userReplyInquiryImage";
    private static final String TAG = InquiryChatActivity.class.getSimpleName();
    @Bind(R.id.titlebar_back_view)
    ImageView titlebarBackView;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.titlebar_right_tv)
    TextView titlebarRightTv;
    public static final String IS_COMPLET = "is_complet";
    public static final String INQUIRY_ID = "inquiryid";
    public static final String GET_DETAIL_INQUIRY = "get_detail_inquiry";
    public static final String DOCTOR_LIST_BEAN = "doctor_list_bean";
    public static final String UPLOAD_IMAGE = "uploadImage";

    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;

    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.input_menu)
    EaseChatInputMenu inputMenu;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.rl_question_title)
    RelativeLayout rlQuestionTitle;
    @Bind(R.id.tv_question_info)
    TextView tvQuestionInfo;
    @Bind(R.id.tv_time_history)
    TextView tvTimeHistory;
    @Bind(R.id.tv_question_status)
    TextView tvQuestionStatus;
    @Bind(R.id.ll_question_content)
    LinearLayout llQuestionContent;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.tv_time)
    TextView tvTime;
    public InquiryChatActivity activityInstance;
    @Bind(R.id.gv_images)
    GridView gvImages;
    private String toChatUsername;
    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;
    private UserInfo userInfo;
    protected int pagesize = 20;
    private String inquiryId;
    private InquiryDetailBean mDetailBean;
    protected File cameraFile;
    private boolean isComplete;
    private boolean isOpen = true;
    Gson gson = new Gson();
    private InquiryChatListAdapter inquiryChatListAdapter;
    private String msg;
    private List<ChatMessageVo> messages;
    private InquiryDetailBean.DoctorlistBean doctorBean;
    ArrayList<String> urls = new ArrayList<String>();
    private InquiryDetailBean.ContentBean contentBean;
    private ImageView[] imageViews;
    List<InquiryDetailBean.DoctorlistBean.InquiryreplylistBean> list;
    private boolean isSetUserInfo;
    private DetailGridViewAdapter mGridViewAdapter;
    //扩展栏
    protected int[] itemStrings = {R.string.chat_picture, R.string.chat_camera};
    protected int[] itemdrawables = {R.drawable.ic_chat_picture, R.drawable.ic_chat_camera,};
    protected int[] itemIds = {ITEM_PICTURE, ITEM_TAKE_PICTURE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityInstance = this;
        userInfo = PreferenceHelper.getUser();
        Bundle consultBundle = getIntent().getExtras();
        inquiryId = consultBundle.getString(INQUIRY_ID);//问诊id
        toChatUsername = consultBundle.getString(EaseConstant.EXTRA_USER_ID);//聊天人id
        isComplete = consultBundle.getBoolean(IS_COMPLET, false);
        doctorBean = (InquiryDetailBean.DoctorlistBean) consultBundle.getSerializable(InquiryChatActivity.DOCTOR_LIST_BEAN);
        EventBus.getDefault().register(this);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_inquiry_chat);
        ButterKnife.bind(this);
        initView();
        initInputView();
        initListener();
    }


    private void initView() {
        View view = LayoutInflater.from(this).inflate(R.layout.sick_person_question, null);
        titlebarRightView.setImageResource(R.drawable.inquiry_question);
        titlebarTitleTv.setText("问诊");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        inquiryChatListAdapter = new InquiryChatListAdapter(this, messages, recyclerView);
        recyclerView.setAdapter(inquiryChatListAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


    }

    private void initInputView() {
        CustomChatPrimaryMenu custom = new CustomChatPrimaryMenu(this);//自定义primary输入栏,不要语音相关view
        inputMenu.setCustomPrimaryMenu(custom);
        inputMenu.init(null);
        //发送监听
        inputMenu.setChatInputMenuListener(new EaseChatInputMenu.ChatInputMenuListener() {
            @Override
            public void onSendMessage(String content) {
                //用户追问
                if (!content.equals("")) {
                    provider.userReplyInquiry(gson.toJson(new ChatMessageVo(content, USER_TEXT_TYPE)), toChatUsername, inquiryId, USER_REPLY_INQUIRY);
                }
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return true;
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
            }
        });
        //初始化扩展栏,这里只有两个,选择照片和拍照
        for (int i = 0; i < 2; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], new MyExtendClickListener());
        }
        inputMenu.getExtendMenu().setNumColumns(2);
    }

    private void initData() {
        provider.getInquiryById(inquiryId, GET_DETAIL_INQUIRY);
    }

    private void initListener() {
        ivMore.setOnClickListener(this);
        rlQuestionTitle.setOnClickListener(this);
        titlebarRightView.setOnClickListener(this);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                inputMenu.hideExtendMenuContainer();
                hideKeyboard();
                return false;
            }
        });
        inquiryChatListAdapter.setOnItemClickLitener(new InquiryChatListAdapter.OnItemClickLitener() {
            @Override
            public void onItemImageClick(View view, int position, String imageUrl) {
                urls.add(imageUrl);
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("imgUrls", urls);
                //bundle.putInt("position", position);
                bundle.putInt("type", PictureActivity.TYPE_NET_IMG);
                ActivityUtils.showActivity(InquiryChatActivity.this, PictureActivity.class, bundle);
                urls.remove(0);
            }
        });
        gvImages.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mDetailBean.getInquiry().getContentBean().getImages().size() > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("imgUrls", mDetailBean.getInquiry().getContentBean().getImages());
                    bundle.putInt("position", 0);
                    bundle.putInt("type", PictureActivity.TYPE_NET_IMG);
                    ActivityUtils.showActivity(InquiryChatActivity.this, PictureActivity.class, bundle);
                }
            }
        });

    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        //得到用户信息
        if (GET_DETAIL_INQUIRY.equals(actionName)) {
            mDetailBean = (InquiryDetailBean) object;
            //根据请求结果设置ui
            if (mDetailBean != null) {
                if (!isSetUserInfo) {
                    setQuestionInfo();
                }
                updateList();
            }
        }

        //用户追问成功

        //文字
        if (USER_REPLY_INQUIRY.equals(actionName)) {
            sendTextMessage(msg);
        }

        //图片
        if (USER_REPLY_INQUIRY_IMG.equals(actionName)) {
            sendImageMessage(userInfo.getHimg());
        }

        //上传图片成功并发送
        if (UPLOAD_IMAGE.equals(actionName)) {
            Log.v("tag", "uploadImage:" + object);
            String url = "" + object;
            if (url != null) {
                if (userInfo != null) {
                    userInfo.setHimg(url);
                }
                provider.userReplyInquiry(gson.toJson(new ChatMessageVo(url, USER_IMG_TYPE)), toChatUsername, inquiryId, USER_REPLY_INQUIRY_IMG);
            }
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_view:
                DialogHelp.showH5Dialog(this, Constants.H5_TIP_SERVICE_TO_EXPLAIN);
                break;
            case R.id.rl_question_title:
                if (isOpen) {
                    //关闭
                    ivMore.setImageResource(R.drawable.home_docinfo_more_down);
                    llQuestionContent.setVisibility(View.GONE);
                    isOpen = false;
                } else {
                    //打开
                    ivMore.setImageResource(R.drawable.home_docinfo_more_up);
                    llQuestionContent.setVisibility(View.VISIBLE);
                    isOpen = true;
                }
                break;
        }
    }

    /**
     * 扩展菜单栏item点击事件
     */
    class MyExtendClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            switch (itemId) {
                case ITEM_TAKE_PICTURE: // 拍照
                    selectPicFromCamera();
                    break;
                case ITEM_PICTURE:
                    selectPicFromLocal(); // 图库选择图片
                    break;
                default:
                    break;
            }
        }
    }
    //接收医生发来的消息
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(ChatMessageVo message) {
        initData();
    }

    //发送消息方法
    //==========================================================================
    private void sendTextMessage(String content) {
        provider.getInquiryById(inquiryId, GET_DETAIL_INQUIRY);
//        ChatMessageVo messageVo = new ChatMessageVo(content,USER_TEXT_TYPE);
//        inquiryChatListAdapter.addItem(messageVo);
    }

    private void sendImageMessage(String content) {
        provider.getInquiryById(inquiryId, GET_DETAIL_INQUIRY);
    }

    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists()) {
                    uploadPic(cameraFile.getAbsolutePath());
                }

            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        uploadPic(getRealFilePath(this, selectedImage));
                    }
                }
            }
        }
    }

    /**
     * 照相获取图片
     */
    protected void selectPicFromCamera() {
        if (!EaseCommonUtils.isExitsSdcard()) {
            Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 从图库获取图片
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }


    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onDestroy() {
        LogUtil.i(TAG, "ondestory");
        super.onDestroy();
    }

    private void setQuestionInfo() {
        isSetUserInfo = true;
        //基本信息行
        tvName.setText(mDetailBean.getInquiry().getUserdesc());
        tvTime.setText(DateUtil.date2String(mDetailBean.getInquiry().getCreatetime(), "yyyy-MM-dd"));
        //问题详情
        String message = mDetailBean.getInquiry().getContentBean().getMessage();
        tvQuestionInfo.setText(message);
        //图片
        if (mGridViewAdapter == null) {
            mGridViewAdapter = new DetailGridViewAdapter(mDetailBean, this);
            gvImages.setAdapter(mGridViewAdapter);
        }
        mGridViewAdapter.notifyDataSetChanged();
        if (mDetailBean.getInquiry().getContentBean().getImages().size() == 0) {
            gvImages.setVisibility(View.GONE);
        }
        //是否关闭

        if (!isComplete) {
            tvQuestionStatus.setVisibility(View.INVISIBLE);
        }
    }


    private void uploadPic(String path) {
        ImageUpLoader upLoader = new ImageUpLoader(InquiryChatActivity.this, InquiryChatActivity.this);
        upLoader.uploadImage(new File(path), new HashMap<String, String>());//
    }

    /**
     * Uri转文件路径
     *
     * @param context
     * @param uri
     * @return
     */
    public String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private void updateList() {
        //追问条数需要实时更新
        String hour = DateUtil.formatDuring(System.currentTimeMillis() - mDetailBean.getInquiry().getCreatetime());
        tvTimeHistory.setText(hour + "小时/" + mDetailBean.getInquiry().getUserreplynum() + "条追问后");
        List<InquiryDetailBean.DoctorlistBean> doctorlist = mDetailBean.getDoctorlist();
        for (InquiryDetailBean.DoctorlistBean doctor : doctorlist) {
            if (doctor.getDoctorid().equals(toChatUsername)) {
                list = doctor.getInquiryreplylist();
            }
        }

        messages = new ArrayList<>();
        Gson g = new Gson();
        for (int i = 0; i < list.size(); i++) {
            ChatMessageVo messageVo = g.fromJson(list.get(i).getContent(), ChatMessageVo.class);
            messageVo.setCreatetime(list.get(i).getCreatetime());
            messages.add(messageVo);
        }
        inquiryChatListAdapter.addAllMessage(messages);
    }


}
